/*************************************************************************
    > File Name: socket.cpp
    > Author: 侯广臣
    > Mail: 2801059691@qq.com 
    > Created Time: 2020年12月30日 星期三 15时22分40秒
 ************************************************************************/

#include "socket.h"

ssize_t CSocket::Recv(char *buf, int bufSize, const int flag)
{
	return recv(m_sockfd, buf, bufSize, flag);
}

//发送信息
ssize_t CSocket::Send(const char *buf, int bufSize, const int flag)
{
	return send(m_sockfd, buf, bufSize, flag);
}

//传输文件，inFd必须为真实文件描述符，成功返回字节数，失败返回 -1
ssize_t CSocket::SendFile(int inFd, size_t count, off_t *offset)
{
	return sendfile(m_sockfd, inFd, offset, count);
}


//如果ip == NULL默认监听所有本地地址，如果m_socket != -1不做动作
//失败返回 -1，成功返回m_socket
int CListenSocket::Init(const char *ip, int port, int backlog)
{
	if(m_sockfd != -1)
	{
		return m_sockfd;
	}

	m_sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(m_sockfd == -1)
	{
		return -1;
	}

	struct sockaddr_in serverAddr;
	memset(&serverAddr, 0, sizeof(serverAddr));
	if(ip == NULL)
	{
		serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
		serverAddr.sin_addr.s_addr = inet_addr(ip);
	}
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(port);

	if(bind(m_sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1)
	{
		close(m_sockfd);
		m_sockfd = -1;
		return -1;
	}

	if(listen(m_sockfd, backlog) == -1)
	{
		close(m_sockfd);
		m_sockfd = -1;
		return -1;
	}

	return m_sockfd;
}

char* CListenSocket::GetClientInfo(char *buf)
{
	if(buf == NULL)
	{
		return NULL;
	}

	if(sprintf(buf, "%s:%d", inet_ntoa(m_clientAddr.sin_addr), ntohs(m_clientAddr.sin_port)) <= 0)
	{
		return NULL;
	}

	return buf;
}
